package com.codingfly.config;

import com.codingfly.filter.CorsFilter;
import com.codingfly.filter.OauthFilter;
import com.codingfly.service.OauthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.List;

@Configuration
public class FilterConfig {

	@Value("${corsFilter.allowOrigin:*}")
	private String allowOrigin;

	@Value("${corsFilter.allowMethods:DELETE,GET,OPTIONS,POST,PUT,PATCH}")
	private String[] allowMethods;

	@Value("${corsFilter.allowHeaders:*}")
	private String allowHeaders;

	@Value("${corsFilter.maxAge:3600}")
	private long maxAge;

	@Autowired
	private OauthService oauthService;

	@Bean
	public FilterRegistrationBean corsFilter() {
		FilterRegistrationBean registration = new FilterRegistrationBean();
		registration.setFilter(new CorsFilter(allowOrigin, allowMethods, allowHeaders, maxAge));
		List<String> urlList = new ArrayList();
		urlList.add("/*");
		registration.setUrlPatterns(urlList);
		registration.setName("corsFilter");
		registration.setOrder(2);
		return registration;
	}

	@Bean
	public FilterRegistrationBean oauthFilter() {
		FilterRegistrationBean registration = new FilterRegistrationBean();
		registration.setFilter(new OauthFilter(oauthService));
		List<String> urlList = new ArrayList();
		urlList.add("/*");
		registration.setUrlPatterns(urlList);
		registration.setName("oauthFilter");
		registration.setOrder(4);
		return registration;
	}

}